package com.trainoo.util;

import org.springframework.beans.factory.annotation.Value;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

public class EmailKit {

    @Value("${email.account}")
    private static String emailAccount;
    @Value("${email.password}")
    private static String emailPassword;
    @Value("${email.host}")
    private static String emailSMTPHost;

    @Value("${email.sendTo}")
    private static String receiveMailAccount;

    private static Session session;

    static {
        // 1. 创建参数配置, 用于连接邮件服务器的参数配置
        Properties props = new Properties();                    // 参数配置
        props.setProperty("mail.transport.protocol", "smtp");   // 使用的协议（JavaMail规范要求）
        props.setProperty("mail.smtp.host", emailSMTPHost);     // 发件人的邮箱的 SMTP 服务器地址
        props.setProperty("mail.smtp.auth", "true");            // 需要请求认证
        // 2. 根据配置创建会话对象, 用于和邮件服务器交互
        session = Session.getInstance(props);
        session.setDebug(true);                                 // 设置为debug模式, 可以查看详细的发送 log
    }

    /**
     * 发送邮件
     */
    public static void send(Message message) throws Exception {
        Transport transport = null;
        try {
            transport = session.getTransport();
            transport.connect(emailAccount, emailPassword);
            transport.sendMessage(message, message.getAllRecipients());
        }finally {
            if(transport != null) {
                transport.close();
            }
        }
    }

    /**
     * 创建一封只包含文本的简单邮件
     */
    public static MimeMessage createMimeMessage(String sendMail, String receiveMail,
                                                String subject, String content)
            throws UnsupportedEncodingException, MessagingException {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(sendMail, "from", "UTF-8"));
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "to", "UTF-8"));
        message.setSubject(subject, "UTF-8");
        message.setContent(content, "text/html;charset=UTF-8");
        message.setSentDate(new Date());
        message.saveChanges();
        return message;
    }
}